<template>
  <div style="border: 1px solid #ccc">
    <Editor
      style="overflow-y: hidden; height: 100vh"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="deal_change"
    />
  </div>
</template>

<script>
import eventBus from '@/eventBus/eventBus'

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { Editor } from '@wangeditor/editor-for-vue'
import { SlateNode } from '@wangeditor/editor'

// 编辑器配置
const editorConfig = {
  placeholder: '',
  readOnly: true
  // scroll: false
}

export default {
  components: { Editor },

  data() {
    return {
      // 内容 HTML
      valueHtml: ref(''),
      show_title_list: [],
      clientHeight: 500
    }
  },

  watch: {
    editorRef: {
      deep: true,
      handler(newvar) {
        this.$emit('trans_editor', newvar)
      }
    }
  },

  methods: {
    // 编辑器内容改变时触发
    deal_change(editor) {
      const headers = editor.getElemsByTypePrefix('header')
      var list = headers.map((header) => {
        const text = SlateNode.string(header)
        const { id, type } = header

        return { id, type, text }
      })

      eventBus.emit('get_show_title_list', list)
    }
  },

  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    return {
      editorRef,
      mode: 'default', // 或 'simple'

      editorConfig,
      handleCreated
    }
  },

  created() {},

  mounted() {
    this.clientHeight = document.body.clientHeight
    window.onresize = () => {
      //屏幕尺寸变化就重新赋值
      return (() => {
        this.clientHeight = document.body.clientHeight
      })()
    }
  }
}
</script>
